import { QuestionCircleOutlined } from '@ant-design/icons'
import { Tooltip } from 'antd'
import dayjs from 'dayjs'
import { useState } from 'react'

import { createBillApi, needMakeBillOrderListApi } from '@/api/pcs/pcsBillManage'
import AekDrawer, { PromiseThen } from '@/components/AekDrawer'
import AekLinkButton from '@/components/AekLinkButton'
import AekTable from '@/components/AekTable'
import SearchForm from '@/components/SearchForm'
import DetailDrawer from '@/pages/pcs/pcsCompanionOrder/components/DetailDrawer'
import { message, modal } from '@/utils/antdHelper'
import { formatDate, formatDateTime } from '@/utils/displayHelper'
import { PCS_COMBO_TYPE_ENUM, PCS_COMPANION_ORDER_STATUS_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const CreateBillModal = () => {
  const [loading, setLoading] = useState(false)
  const [searchParams, setSearchParams] = useState({})
  const [list, setList] = useState([])

  const [selectedRowKeys, setSelectedRowKeys] = useState([])

  const loadList = async (values = {}) => {
    if (!values.billDate) return message.warning('请先选择账单日期')
    const { billDate } = values
    const params = {
      billDate: billDate ?? formatDate(billDate),
    }
    setLoading(true)
    const { data } = await requestWithTry(needMakeBillOrderListApi, params).finally(() => {
      setLoading(false)
    })
    setList(data)
  }

  /** @type {import("@/components/SearchForm").SearchFormProps} */
  const searchProps = {
    searchParams,
    formData: [
      {
        field: 'billDate',
        label: (
          <Tooltip title='服务中订单如果周期过长，通过账单日期拆分当前订单'>
            账单日期
            <QuestionCircleOutlined className='ml10px' />
          </Tooltip>
        ),
        component: {
          name: 'DatePicker',
          props: {
            allowClear: false,
            placeholder: '选择日期',
            disabledDate: currentDate => currentDate.valueOf() > dayjs().subtract(1, 'days').valueOf(),
          },
        },
      },
    ],
    onSearch: values => {
      setSelectedRowKeys([])
      setSearchParams(values)
      loadList(values)
    },
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    showConfig: false,
    configKey: 'CreateBillModal',
    rowKey: 'orderDetailNursingWorkersId',
    loading,
    dataSource: list,
    pagination: false,
    columns: [
      {
        dataIndex: 'orderNo',
        title: '订单号码',
        render: (text, record) => (
          <AekLinkButton
            onClick={() => {
              DetailDrawer.PromiseThen({ id: record.orderId, hideOperate: true })
            }}
          >
            {text}
          </AekLinkButton>
        ),
      },
      { dataIndex: 'status', title: '订单状态', enum: PCS_COMPANION_ORDER_STATUS_ENUM },
      { dataIndex: 'patientName', title: '患者姓名' },
      { dataIndex: 'inpatientWardName', title: '地点' },
      { dataIndex: 'companionComboName', title: '套餐名称' },
      { dataIndex: 'comboType', title: '套餐类型', enum: PCS_COMBO_TYPE_ENUM },
      { dataIndex: 'nursingWorkersName', title: '护工姓名' },
      { dataIndex: 'chargingStandard', title: '收费标准' },
      { dataIndex: 'nursingWorkerSettlement', title: '护工结算' },
      {
        dataIndex: 'createTime',
        title: '工单创建时间',
        render: (text, record) => formatDateTime(record.createTime || record.createBillTime),
      },
      {
        dataIndex: 'startDate',
        title: '服务开始时间',
        render: (text, record) => `${formatDate(record.startDate)} ${record.startPeriodRange}`,
      },
      {
        dataIndex: 'endDate',
        title: '服务结束时间',
        // render: (text, record) => `${formatDate(record.endDate)} ${record.endPeriodRange}`,
        render: () => '',
      },
    ],
    rowSelection: {
      onChange: (keys, rows) => {
        setSelectedRowKeys(keys)
      },
      selectedRowKeys,
    },
  }

  return (
    <AekDrawer
      title='手工建账'
      width='90%'
      okButtonProps={{
        disabled: !searchParams.billDate || !selectedRowKeys.length,
      }}
      onOk={async () => {
        const { billDate = [] } = searchParams
        modal.confirm({
          title: '生成账单',
          content: `已选订单的服务开始时间 ~ ${formatDate(billDate)} 12点后`,
          onOk: async () => {
            await requestWithTry(createBillApi, {
              billDate,
              orderDetailNursingWorkersIdList: selectedRowKeys,
            })
            // await loadList(values)
            message.success('操作成功')
          },
        })
      }}
    >
      <div className='flex h-full flex-col'>
        <SearchForm {...searchProps} />
        <AekTable {...tableProps} />
      </div>
    </AekDrawer>
  )
}
CreateBillModal.PromiseThen = PromiseThen

export default CreateBillModal
